package com.mogist.hqc.module.order.ui

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.Gravity
import android.view.WindowManager
import android.widget.EditText
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPFragment
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.response.OrderListVo
import com.mogist.hqc.entitys.response.OrderVo
import com.mogist.hqc.module.order.adapter.OrderAdapter
import com.mogist.hqc.module.order.contract.OrderContract
import com.mogist.hqc.module.order.presenter.OrderPresenter
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.util.Constant
import kotlinx.android.synthetic.main.activity_comment_list.*
import kotlinx.android.synthetic.main.fragment_order.*
import kotlinx.android.synthetic.main.fragment_order.mSwipeToLoadLayout
import kotlinx.android.synthetic.main.fragment_order.swipe_target
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import talex.zsw.basecore.util.KeyboardTool
import talex.zsw.basecore.util.RegTool
import talex.zsw.basecore.view.other.RxToast
import talex.zsw.basecore.view.other.swipetoloadlayout.OnLoadMoreListener
import talex.zsw.basecore.view.other.swipetoloadlayout.OnRefreshListener
import talex.zsw.basecore.view.recyleview.DividerItemDecoration
import talex.zsw.basecore.view.recyleview.SampleFooter
import talex.zsw.basecore.view.recyleview.SampleHeader

/**
 * 作用：订单列表
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class OrderFragment : BaseMVPFragment<OrderContract.Presenter>(), OrderContract.View, OnRefreshListener, OnLoadMoreListener
{
    private var position = 0 // 0:全部  1:待付款  2:待出行  3:待评价
    override fun initArgs(bundle: Bundle?)
    {
        bundle?.getInt("position")
                ?.let {
                    position = it
                }
    }

    override fun initView(bundle: Bundle?)
    {
        setContentView(R.layout.fragment_order)
        mPresenter = OrderPresenter(this)
    }

    override fun initData()
    {
        initRecyclerView()
    }

    override fun onResume()
    {
        if (isRefresh)
        {
            onRefresh()
        }
        super.onResume()
    }

    override fun onVisible()
    {
        if (adapter.itemCount == 0)
        {
            getData(false)
        }
    }

    private val adapter = OrderAdapter()

    private fun initRecyclerView()
    {
        adapter.setOnItemClickListener { adapter, view, position ->
            if (!isFastClick)
            {
                val vo = adapter.getItem(position) as OrderVo
                val intent = Intent(activity, OrderDetailActivity::class.java)
                intent.putExtra("orderNo", vo.orderNo)
                start(intent)
            }
        }
        adapter.setOnItemChildClickListener { adapter, view, position ->
            // iTvCancel iTvRefund iTvComment iTvPay
            if (!isFastClick)
            {
                val vo = adapter.getItem(position) as OrderVo
                when (view.id)
                {
                    R.id.iTvCancel  ->
                    { // 订单取消
                        errorTitle = "取消订单"
                        cancelOrder(vo.orderNo)
                    }
                    R.id.iTvRefund  ->
                    { // 订单退款
                        errorTitle = "退单"
                        cancelOrder(vo.orderNo)
                    }
                    R.id.iTvComment ->
                    { // 订单评价
                        errorTitle = "订单评价"
                        showCommentDialog(vo.orderNo)
                    }
                    R.id.iTvPay     ->
                    { // 支付
                        val intent = Intent(activity, OrderPayActivity::class.java)
                        intent.putExtra("order", vo)
                        start(intent)
                    }
                }
            }
        }
        adapter.emptyView = SampleHeader(activity, swipe_target.width, swipe_target.height)
        adapter.isUseEmpty(false)
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        swipe_target.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL_LIST,
                                                             R.color.transparent))
        swipe_target.layoutManager = LinearLayoutManager(activity)
        swipe_target.adapter = adapter
        // mRecyclerView.isNestedScrollingEnabled = false
        mSwipeToLoadLayout.setOnRefreshListener(this)
        mSwipeToLoadLayout.setOnLoadMoreListener(this)
        mSwipeToLoadLayout.isLoadMoreEnabled = true
        mSwipeToLoadLayout.isRefreshEnabled = true
    }

    // --------------- 数据获取 ---------------
    override fun onDestroy()
    {
        super.onDestroy()
        adapter.removeAllFooterView()
        sampleFooter = null
    }

    override fun getData(silence: Boolean)
    {
        isRefresh = false
        disLoading()
        val body = BaseModel(true)
        body.page = page.toString()
        if (position == 1)
        {
            body.orderStatus = "NEW"
            body.payStatus = "UNPAY"
        }
        else if (position == 2)
        {
            body.orderStatus = "SUCCESS"
            body.payStatus = "PAYED"
        }
        else if (position == 3)
        {
            body.orderStatus = "FINISH"
            body.payStatus = "PAYED"
        }
        mPresenter.getData(HttpDto(Constant.ORDER_LIST,
                                   body).setType(HttpDto.GET).setErrorTitle("获取订单列表失败"))
    }

    var sampleFooter: SampleFooter? = null
    override fun bindData(data: OrderListVo)
    {
        adapter.isUseEmpty(true)
        if (data.list != null && data.list.isNotEmpty())
        {
            if (page == 1)
            {
                adapter.replaceData(data.list)
            }
            else
            {
                adapter.addData(data.list)
            }
            if (data.pages == page)
            {
                sampleFooter
                        ?: let {
                            sampleFooter = SampleFooter(activity)
                        }
                adapter.setFooterView(sampleFooter)
                mSwipeToLoadLayout.isLoadMoreEnabled = false
            }
            page++
        }
        else
        {
            if (page == 1)
            {
                adapter.replaceData(arrayListOf())
                mSwipeToLoadLayout.isLoadMoreEnabled = false
            }
        }
    }

    private var page = 1
    override fun disLoading()
    {
        mSwipeToLoadLayout.isLoadingMore = false
        mSwipeToLoadLayout.isRefreshing = false
    }

    override fun onRefresh()
    {
        adapter.removeAllFooterView()
        page = 1
        mSwipeToLoadLayout.isLoadMoreEnabled = true
        mSwipeToLoadLayout.isRefreshEnabled = true
        getData(true)
    }

    override fun onLoadMore()
    {
        getData(true)
    }

    // --------------- 取消订单/退单 ---------------
    private var errorTitle = ""
    private fun cancelOrder(orderNo: String)
    {
        val body = BaseModel(true)
        body.orderNo = orderNo
        mPresenter.getData(HttpDto(Constant.ORDER_CANCEL, body).setTryAgain(true).setErrorTitle(
                errorTitle + "失败"))
    }

    override fun cancelSuccess()
    {
        EventBus.getDefault().post(Constant.EVENT_REFRESH_ORDER)
        RxToast.success(errorTitle+"成功")
        onRefresh()
    }

    // --------------- 评论 ---------------
    private var dialog: Dialog? = null
    private var dEditText: EditText? = null
    private var commentStr = ""
    private fun showCommentDialog(orderNo: String)
    {
        dialog
                ?: let {
                    dialog = Dialog(activity, R.style.dialog)
                    dialog?.setContentView(R.layout.dialog_comment)
                    dialog?.setCanceledOnTouchOutside(true)
                    val display = activity!!.window.windowManager.defaultDisplay
                    val layoutParams: WindowManager.LayoutParams = dialog?.window!!.attributes
                    layoutParams.width = (display.width * 1).toInt()
                    // layoutParams.height = (display.height * 0.8f).toInt()
                    layoutParams.gravity = Gravity.BOTTOM
                    if (layoutParams.gravity == Gravity.BOTTOM)
                    {
                        layoutParams.y = 0
                    }
                    dialog?.window!!.attributes = layoutParams

                    dEditText = dialog?.findViewById<EditText>(R.id.dEditText)
                    dialog?.findViewById<TextView>(R.id.dTvSure)
                            ?.setOnClickListener {
                                commentStr =
                                        dEditText!!.text.toString()
                                                .trim()
                                if (RegTool.isEmpty(commentStr))
                                {
                                    RxToast.warning("请输入评论信息")
                                }
                                else
                                {
                                    // 项目评论
                                    val body = BaseModel(true)
                                    body.orderNo = orderNo
                                    body.remark = commentStr
                                    mPresenter.getData(HttpDto(Constant.ORDER_COMMENT,
                                                               body).setErrorTitle("发表评论失败"))
                                }
                            }
                    dialog?.findViewById<TextView>(R.id.dTvCancel)
                            ?.setOnClickListener {
                                dialog?.dismiss()
                            }
                }
        dEditText?.setText("")
        KeyboardTool.showSoftInput(activity, dEditText)
        dialog?.show()
    }

    override fun commentSuccess()
    {
        EventBus.getDefault().post(Constant.EVENT_REFRESH_ORDER)
        RxToast.success("评论成功")
        dialog?.dismiss()
        onRefresh()
    }

    // --------------- EventBus ---------------
    private var isRefresh = false

    @Subscribe
    fun onEvent(event: String)
    {
        if (Constant.EVENT_REFRESH_ORDER== event)
        {
            isRefresh = true
        }
        else if (Constant.EVENT_PAY_SUCCESS == event)
        {
            isRefresh = true
        }
    }

}